package com.cgsd.heyu.ui;


import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import androidx.annotation.DrawableRes;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import com.android.library.adapter.OnViewHelper;
import com.android.library.adapter.ViewHelper;
import com.android.library.utils.BeanUtils;
import com.android.library.utils.StringUtils;
import com.android.library.utils.ToastHelper;
import com.cgsd.heyu.R;
import com.cgsd.heyu.http.ErrorMessage;
import com.cgsd.heyu.http.ExceptionHandler;
import com.cgsd.heyu.http.GlobalErrorMessage;
import com.cgsd.heyu.widgets.CommonProgressDialog;
import com.cgsd.heyu.widgets.ErrorCustomView;

import org.greenrobot.eventbus.EventBus;

/**
 * @author Created by Administrator on 2018/4/26.
 */
public abstract class BaseFragment extends Fragment {
    protected int page = 1;
    private CommonProgressDialog mSubmitDialog;
    /**
     * 控件是否初始化完成
     */
    private boolean isViewCreated;
    /**
     * 数据是否已加载完毕
     */
    private boolean isLoadDataCompleted;
    protected OnFragmentInteractionListener mListener;
    protected Context mContext;
    protected View mRootView;
    protected FrameLayout mFrameLayout;
    /**
     * 默认布局
     */
    protected View mErrorView;
    /**
     * 业务逻辑布局
     */
    protected View mContentView;
    /**
     * 默认错误页面
     */
    protected ErrorCustomView mErrorCustomView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mRootView = inflater.inflate(R.layout.fragment_base, container, false);
        init();
        initView();
        isViewCreated = true;
        return mRootView;
    }

    private void init() {
        mFrameLayout = mRootView.findViewById(R.id.view_content);
        if (useCustomLayout() == null) {
            mErrorView = LayoutInflater.from(mContext).inflate(R.layout.layout_timeout, mFrameLayout, false);
            mErrorCustomView = mErrorView.findViewById(R.id.mErrorView);
        } else {
            mErrorView = useCustomLayout();
        }
        mContentView = LayoutInflater.from(mContext).inflate(getLayoutResId(), mFrameLayout, false);
        mFrameLayout.addView(mContentView);
        mFrameLayout.addView(mErrorView);

        loadSuccess();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (isRegisterEventBus()) {
            registerEventBus(this);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (isRegisterEventBus()) {
            unregisterEventBus(this);
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        loadData();
    }

    /**
     * 子类必须实现
     *
     * @return 布局id
     */
    protected abstract int getLayoutResId();

    /**
     * 初始化资源
     */
    protected abstract void initView();

    /**
     * 加载数据
     */
    protected abstract void initData();

    protected void loadData() {
        isLoadDataCompleted = true;
        initData();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = context;
        try {
            mListener = (OnFragmentInteractionListener) context;
        } catch (Exception e) {
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @SuppressWarnings("unchecked")
    public <T extends View> T findViewById(int id) {
        T result = (T) mRootView.findViewById(id);
        if (result == null) {
            throw new IllegalArgumentException("view 0x" + Integer.toHexString(id) + " doesn't exist");
        }
        return result;
    }

    public interface OnFragmentInteractionListener {
        /**
         * fragment回到到activity
         *
         * @param uri
         * @param action
         */
        void onFragmentInteraction(Object uri, String action);

    }

    /**
     * 是否已经注册过
     *
     * @param subscribe
     * @return
     */
    public boolean isEventBusRegisted(Object subscribe) {
        return EventBus.getDefault().isRegistered(subscribe);
    }

    /**
     * 注册EventBus
     *
     * @param subscribe
     */
    public void registerEventBus(Object subscribe) {
        if (!isEventBusRegisted(subscribe)) {
            EventBus.getDefault().register(subscribe);
        }
    }

    /**
     * 反注册EventBus
     *
     * @param subscribe
     */
    public void unregisterEventBus(Object subscribe) {
        if (isEventBusRegisted(subscribe)) {
            EventBus.getDefault().unregister(subscribe);
        }
    }

    /**
     * 是否注册事件分发
     *
     * @return true绑定EventBus事件分发，默认不绑定，子类需要绑定的话复写此方法返回true.
     */
    protected boolean isRegisterEventBus() {
        return false;
    }

    /**
     * Toast提示
     */
    protected void showToast(String content) {
        ToastHelper.showDefaultToast(content);
    }

    /**
     * 实例化对应layoutId的view同时生成ViewHelper帮助类
     *
     * @param group    可为null
     * @param layoutId
     * @param listener
     * @return
     */
    protected View getHelperView(ViewGroup group, int layoutId, OnViewHelper listener) {
        ViewHelper helper = new ViewHelper(getLayoutInflater().inflate(layoutId, group == null ? null : group instanceof RecyclerView ? (ViewGroup) group.getParent() : group, false));
        if (listener != null) {
            listener.help(helper);
        }
        return helper.getItemView();
    }

    /******************-----------------------------------------同意错误处理（提示和页面显示）------------------------------------------------***********/

    /**
     * 处理error
     *
     * @param errorMessage
     */
    protected void handleErrorAction(ErrorMessage errorMessage) {
        //需要登录
        if (errorMessage.getCode() == GlobalErrorMessage.ErrorCode.ERROR_CODE_5557 || errorMessage.getCode() == GlobalErrorMessage.ErrorCode.ERROR_CODE_5558
                || errorMessage.getCode() == GlobalErrorMessage.ErrorCode.ERROR_CODE_5556) {
            if (mContext instanceof BaseActivity) {
                ((BaseActivity) mContext).showConfirmDialog(errorMessage.getMessage());
            }
        } else if (!BeanUtils.isEmpty(errorMessage) && errorMessage.getCode() != ExceptionHandler.Error.UNKNOWN) {
            if (!errorMessage.getMessage().equals("成功")) {
                ToastHelper.showDefaultToast(errorMessage.getMessage());
            }
        }
    }

    /**
     * 页面加载中
     */
    protected void showLoading() {
        mErrorView.setVisibility(View.VISIBLE);
        mContentView.setVisibility(View.GONE);
        mErrorCustomView.showLoading();
    }

    /**
     * 页面加载完成
     */
    protected void loadSuccess() {
        mErrorView.setVisibility(View.GONE);
        mContentView.setVisibility(View.VISIBLE);
    }

    /**
     * 页面数据为空
     */
    protected void showEmptyView() {
        mErrorView.setVisibility(View.VISIBLE);
        mContentView.setVisibility(View.GONE);
        mErrorCustomView.showEmpty();
    }

    /**
     * 页面数据为空
     *
     * @param drawableResId
     */
    protected void showEmptyView(@DrawableRes int drawableResId, String title) {
        mErrorView.setVisibility(View.VISIBLE);
        mContentView.setVisibility(View.GONE);
        mErrorCustomView.showEmpty(drawableResId, title);
    }

    /**
     * 网络错误
     */
    protected void showNetworkError() {
        mErrorView.setVisibility(View.VISIBLE);
        mContentView.setVisibility(View.GONE);
        mErrorCustomView.showNetworkError();
    }

    /**
     * 网络错误
     */
    protected void showNetworkError(@DrawableRes int drawableResId, String title) {
        mErrorView.setVisibility(View.VISIBLE);
        mContentView.setVisibility(View.GONE);
        mErrorCustomView.showNetworkError(drawableResId, title);
    }

    /**
     * 自定义错误页面
     * 默认错误页面 {@link ErrorCustomView}
     *
     * @return
     */
    protected View useCustomLayout() {
        return null;
    }

    /**
     * 加载进度显示
     */
    public void showSubmitDialog() {
        showLoadingView("");
    }

    /**
     * 加载进度显示
     *
     * @param msg
     */
    public void showLoadingView(String msg) {
        if (mSubmitDialog == null) {
            mSubmitDialog = new CommonProgressDialog(getActivity(), R.style.dialog_common_loading, StringUtils.isNotEmpty(msg) ? msg : "加载中...");
        }
        mSubmitDialog.show();
    }

    /**
     * 关闭提交数据统一加载进度条
     */
    protected void dismissCommonSubmitDialog() {
        if (mSubmitDialog != null && mSubmitDialog.isShowing()) {
            mSubmitDialog.dismiss();
        }
    }


}
